# 生成器 使用一个就少一个元素
g = (x * x for x in range(10))
print(next(g))
print(next(g))
print(next(g))
for a in g:
    if a < 17:
        print(a * a)


def fib(num):  # 斐波拉契数列 函数
    n, p, q = 0, 0, 1
    while n < num:
        print(q)
        p, q = q, p + q
        n = n + 1
    return 'done'


print(fib(5))


def fib2(num):  # 斐波拉契数列 函数
    n, p, q = 0, 0, 1
    while n < num:
        yield q
        p, q = q, p + q
        n = n + 1
    return 'done'


ff = fib2(6)
print(next(ff))

# 但是用for循环调用generator时，发现拿不到generator的return语句的返回值。如果想要拿到返回值，必须捕获StopIteration错误，返回值包含在StopIteration的value中：

while True:
    try:
        x = next(ff)
        print('g:', x)
    except StopIteration as e:
        print('Generator return value:', e.value)
        break


# 输出杨辉三角